package com.baymax.test.scene.internal;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import java.util.concurrent.TimeUnit;

/**
 * 21 号组件。
 *
 * @author yangliangwei
 * @date 2022-05-27
 */
public class Module21View extends RecyclerView {
    private Module21LayoutManager layoutManager;

    public Module21View(Context context) {
        super(context);
        init();
    }

    public Module21View(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public Module21View(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        layoutManager = new Module21LayoutManager(getContext());
        super.setLayoutManager(layoutManager);
        setBackgroundColor(Color.RED);
        setChildDrawingOrderCallback(new ChildDrawingOrderCallback() {
            @Override
            public int onGetChildDrawingOrder(int childCount, int i) {
                if (!hasFocus()) {
                    return i;
                }
                View focusedChild = getFocusedChild();
                if (focusedChild == null) {
                    return i;
                }
                int index = getChildLayoutPosition(focusedChild);
                if (i == childCount - 1) {
                    return index;
                } else if (i < index) {
                    return i;
                } else {
                    return i + 1;
                }
            }
        });
    }

    @Override
    public void setAdapter(Adapter adapter) {
        super.setAdapter(adapter);
    }

    public void setChildSizeLookup(ChildSizeLookup lookup) {
        layoutManager.setChildSizeLookup(lookup);
    }

    public ChildSizeLookup getChildSizeLookup() {
        return layoutManager.getChildSizeLookup();
    }

    @Override
    public void setLayoutManager(LayoutManager layout) {
        throw new UnsupportedOperationException("Module21View 不支持自定义 LayoutManager 。");
    }

    static class Module21LayoutManager extends LayoutManager {
        /**
         * 布局排版的基准宽度（基于 1080P）。
         */
        private static final int BASE_WIDTH = 1920;
        private final Context context;
        private ChildSizeLookup lookup;
        private final Rect tmp = new Rect();

        Module21LayoutManager(Context context) {
            this.context = context;
        }

        public void setChildSizeLookup(ChildSizeLookup lookup) {
            this.lookup = lookup;
        }

        public ChildSizeLookup getChildSizeLookup() {
            return lookup;
        }

        @Override
        public LayoutParams generateDefaultLayoutParams() {
            return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        }

        @Override
        public void onMeasure(@NonNull Recycler recycler, @NonNull State state, int widthSpec, int heightSpec) {
            setMeasuredDimension(this.context.getResources().getDisplayMetrics().widthPixels , lookup.totalHeight());
        }

        @Override
        public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
            if (state.isPreLayout()) {
                return;
            }
            if (getItemCount() == 0) {
                removeAndRecycleAllViews(recycler);
                return;
            }
            ChildSizeLookup lookup = this.lookup;
            if (lookup == null) {
                Log.w("aaa", "onLayoutChildren: not set lookup");
                return;
            }

            long start = SystemClock.elapsedRealtimeNanos();
            int count = getItemCount();
            detachAndScrapAttachedViews(recycler);

            for (int i = 0; i < getItemCount(); i++) {
                View view = recycler.getViewForPosition(i);
                addView(view);

                tmp.setEmpty();
                lookup.getSize(view, i, tmp);

                ViewGroup.LayoutParams params = view.getLayoutParams();
                boolean relayout = false;
                if (params.width != tmp.width()) {
                    Log.d("aaa", "tmp Rect:width" + params.width +","  + tmp.width());
                    params.width = tmp.width();
                    relayout = true;
                }
                if (params.height != tmp.height()) {
                    Log.d("aaa", "tmp Rect:height" + params.height +","  + tmp.height());
                    params.height = tmp.height();
                    relayout = true;
                }

                if (tmp.left != view.getLeft() || tmp.top != view.getTop()){
                    Log.d("aaa", "tmp Rect:left|top" );
                    relayout = true;
                }
                if (relayout) {
                    measureChild(view, 0, 0);
                    layoutDecoratedWithMargins(view, tmp.left, tmp.top, tmp.right, tmp.bottom);
                }
                //Log.d("aaa", "tmp Rect:" + tmp + ", l:"  + view  +"relayout:" + relayout);

            }
            Log.d("aaa", "onLayoutChildren count: " + count + ", lookup" + lookup + ",  cost time = " + TimeUnit.NANOSECONDS.toMillis((SystemClock.elapsedRealtimeNanos() - start)) + "ms");
        }

        @Override
        public boolean canScrollHorizontally() {
            return false;
        }

        @Override
        public boolean canScrollVertically() {
            return false;
        }

        @Override
        public void onDetachedFromWindow(RecyclerView view, RecyclerView.Recycler recycler) {
            super.onDetachedFromWindow(view, recycler);
            this.removeAndRecycleAllViews(recycler);
            recycler.clear();
        }
    }
}
